package org.goyo.main.web.controller.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.goyo.common.baseBean.AjaxResult;
import org.goyo.common.baseBean.Constants;
import org.goyo.common.exception.DBException;
import org.goyo.common.exception.ServiceException;
import org.goyo.common.utils.JSONUtil;
import org.goyo.common.utils.Pager;
import org.goyo.common.utils.ToolUtils;
import org.goyo.main.domain.entity.BaseObject;
import org.goyo.main.domain.entity.base.Categories;
import org.goyo.main.domain.entity.base.SupplierClassification;
import org.goyo.main.domain.entity.base.Warehouse;
import org.goyo.main.domain.entity.system.SysDepGroup;
import org.goyo.main.services.base.ICategoriesService;
import org.goyo.main.services.log.MethodLog;
import org.goyo.main.web.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 商品分类
 * @author liu
 *
 */
@Controller
@RequestMapping("/categories")
public class CategoriesController extends BaseController {
  protected Logger logger = LoggerFactory.getLogger(this.getClass());

  @Resource
  private ICategoriesService categoriesService;

  /**
   * 列表界面
   * 
   * @author chenchuan 2014年11月9日
   */
  @RequestMapping("/toCategoriesList")
  public String toCategoriesList(Model model) {
    List<Categories> list = null;
    try {
        list = categoriesService.getAllCategories();
        if(null==list||list.size()==0){
          list  = new ArrayList<Categories>();
          Categories sc  = new Categories();
          sc.setName("初始化节点");
          sc.setParentId("");
          //sc.setUuid("1234");
          list.add(sc);
        }
        model.addAttribute("list", JSONUtil.obj2Json(list));
    } catch (Exception e) {
      logger.error(e.getMessage(),e);
    }
    return "/base/CategoriesList";
  }
  
  /**
   * 列表界面
   * 
   * @author
   */
  @RequestMapping("/categoriesList")
  @ResponseBody
  public String categoriesList(Model model) {
    List<Categories> list = null;
    try {
        list = categoriesService.getAllCategories();
        if(null==list||list.size()==0){
          list  = new ArrayList<Categories>();
          Categories sc  = new Categories();
          sc.setName("初始化节点");
          sc.setParentId("");
          //sc.setUuid("1234");
          list.add(sc);
        }
        return JSONUtil.obj2Json(list).toString();
    } catch (Exception e) {
      logger.error(e.getMessage(),e);
    }
    return null;
  }

  /**
   * 保存或者更新
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("保存或者更新商品分类信息")
  @RequestMapping("/saveOrUpdateCategories")
  @ResponseBody
  public AjaxResult saveOrUpdateCategories(Categories categories,HttpServletRequest request) {
    AjaxResult result = null;
    try {
    //  Categories categoriesBean = JSONUtil.json2Obj(categories, Categories.class);
      String uuid = categoriesService.saveOrUpdateInfo(categories);
      List<Categories> list =categoriesService.getAllCategories();
      result = AjaxResult.resultSuccess("保存成功", list,uuid);
    } catch (Exception e) {
      if(e.getMessage().contentEquals("Duplicate entry")){
        System.out.println(e.getMessage());
      }
      logger.error(e.getMessage(),e);
      result = AjaxResult.resultFail("保存失败,请确认编号唯一。", null);
    }
    return result;
  }

  /**
   * 删除
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("删除商品分类信息")
  @RequestMapping("/delCategories")
  @ResponseBody
  public AjaxResult delCategories(HttpServletRequest request) {
    /*AjaxResult result = null;
    try {
      String rows = request.getParameter("rows");
      JSONArray jsonarray = JSONArray.fromObject(rows);
      List<Categories> list = (List<Categories>) JSONArray.toCollection(jsonarray, Categories.class);
      categoriesService.delByUuids(ToolUtils.getFiles(list, "uuid").toArray());
      result = AjaxResult.resultSuccess("删除成功", null);
    } catch (Exception e) {

    }
    return result;*/
    

    AjaxResult result = null;
    try {
        String uuid = request.getParameter("uuid");
        categoriesService.delByUuids(new String[]{uuid});
        List<Categories> list =categoriesService.getAllCategories();
        result = AjaxResult.resultSuccess("删除成功", list);
    } catch (Exception e) {
      logger.error(e.getMessage(),e);
    }
    return result;

  }

  /**
   * 查看
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("查看商品分类信息")
  @RequestMapping("/viewCategories")
  public String viewCategories(HttpServletRequest request, Model model) {
    String uuid = request.getParameter("uuid");
    Categories info = null;
    try {
      info = categoriesService.findByUuid(uuid);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    model.addAttribute("info", JSONUtil.obj2Json(info));
    model.addAttribute("status", Constants.VIEW);
    return "/base/CategoriesEdit";
  }

/*  *//**
   * 修改
   * 
   * @author chenchuan 2014年11月9日
   *//*
  @MethodLog("修改商品分类信息")
  @RequestMapping("/alterCategories")
  public String alterCategories(HttpServletRequest request, Model model) {
    String uuid = request.getParameter("uuid");
    Categories info = null;
    try {
      info = categoriesService.findByUuid(uuid);
    } catch (Exception e) {

    }
    model.addAttribute("info", JSONUtil.obj2Json(info));
    model.addAttribute("status", Constants.EDIT);
    return "/base/CategoriesEdit";
  }*/

  /**
   * 添加
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("新增商品分类信息")
  @RequestMapping("/addCategories")
  public String addCategories(HttpServletRequest request,Model model) {
    try {
      String uuid = request.getParameter("uuid");
      if(!StringUtils.isEmpty(uuid)){
        Categories c =
        categoriesService.findByUuid(uuid);
        if(null!=c && !StringUtils.isEmpty(c.getParentId())){
          c.setParentName(categoriesService.findByUuid(c.getParentId()).getName());
        }
        model.addAttribute("categories_data",JSONUtil.obj2Json(c));
        model.addAttribute("status", Constants.EDIT);
      }else{
        model.addAttribute("number",categoriesService.getCategoriesSerialNumber());
        model.addAttribute("status", Constants.NEW);
      }
    } catch (Exception e) {
      logger.error(e.getMessage(),e);
    }
    return "/base/CategoriesEdit";
  
  /*  String data = request.getParameter("data");
    Categories categories = JSONUtil.json2Obj(data, Categories.class);
      Map<String,String> map = new HashMap<String, String>();
      try {
        if(StringUtils.isEmpty(categories.getNumber())){
          categories.setNumber(categoriesService.getCategoriesSerialNumber());
        }
    } catch (DBException | ServiceException e) {
      logger.error(e.getMessage(),e);
    }
      return  "/base/CategoriesEdit";*/
  
    }

  /**
   * list列表数据加载
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("查询商品分类信息")
  @RequestMapping("/listData")
  @ResponseBody
  public String ListData(HttpServletRequest request) {
    JSONObject data = null;
    // 获取条件
    // Map<String, Object> cond = JSONUtil.json2Map(request.getParameter("cond"));
    // 分页条件
    int page = Integer.parseInt(request.getParameter("page"));
    int pageSize = Integer.parseInt(request.getParameter("pagesize"));
    String sortname = request.getParameter("sortname");
    String sortorder = request.getParameter("sortorder");
    String leaf = request.getParameter("leaf");
    String where = request.getParameter("where");
    if(leaf != null && !"".equals(leaf)){
      if(where != null && !"".equals(where)){
          where = where + "and leaf = '"+leaf+"'";
      }else{
          where ="leaf = '"+leaf+"'";
      }
  }
    // 分页器
    Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
    try {
      pager = categoriesService.findByCondition(where, pager);
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("Rows", pager.getList());
      map.put("Total", pager.getCount());
      data = JSONObject.fromObject(map);
    } catch (Exception e) {
        logger.error(e.getMessage(),e);
    }
    return data.toString();
  }
}
